package com.xxl.vueadmin.controller;


import cn.hutool.core.map.MapBuilder;
import com.xxl.vueadmin.common.Result;
import com.xxl.vueadmin.entity.SysMenu;
import com.xxl.vueadmin.entity.SysUser;
import com.xxl.vueadmin.entity.dto.SysMenuDto;
import io.jsonwebtoken.JwtException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.List;

/**
 * <p>
 *  权限菜单前端控制器
 * </p>
 *
 * @author xu
 * @since 2021-07-28
 */
@RestController
@RequestMapping("/sys/menu/")
public class SysMenuController extends BaseController {
    @RequestMapping("test")
    public Result test() {
        return Result.success(null);
    }

    @GetMapping("nav")
    public Result getNav(Principal principal) {
        SysUser user = sysUserService.getBayUserName(principal.getName());
        if(user == null) {
            throw new JwtException("身份信息错误,请重新登录");
        }
        // 获取权限信息
        String authorityStr = sysUserService.gerUserAuthority(user.getId());
        String[] authorityArr = authorityStr.split(",");

        // 获取菜单和权限信息
        List<SysMenuDto> userMenu = sysMenuService.getCurrUserNav(user.getId());
        return Result.success(MapBuilder.create().put("authoritys", authorityArr)
                                                 .put("nav", userMenu)
                                                 .map());
    }
    @GetMapping("info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    public Result getMenuInfo(@PathVariable String id) {
        return  Result.success(sysMenuService.getById(id));
    }

    @GetMapping("list")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    public Result getMenuTree() {
        return  Result.success(sysMenuService.getTree());
    }

    @PostMapping("save")
    @PreAuthorize("hasAnyAuthority('sys:menu:save')")
    public Result saveMenu(@Validated @RequestBody SysMenu sysMenu) {
        sysMenuService.save(sysMenu);
        return Result.success("添加成功");
    }
    @PostMapping("edit")
    @PreAuthorize("hasAnyAuthority('sys:menu:update')")
    public Result editMenu(@Validated @RequestBody SysMenu sysMenu) {
        sysMenuService.updateById(sysMenu);
        return Result.success("修改成功");
    }
    @DeleteMapping("remove/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:delete')")
    public  Result removeMenu(@PathVariable String id) {
        Result result = sysMenuService.removeMenu(id);
        sysUserService.clearMenuAuthority(id);
        return result;
    }
}
